/* 
 * Copyright (c) 2019, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.admin.sys.config;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDeletedEvent;
import org.springframework.session.events.SessionExpiredEvent;
import com.cory.admin.sys.domain.AdminPrincipal;
import com.cory.admin.sys.service.SysLoginLogService;
import com.cory.boot.component.cache.RedisUtils;
import com.cory.boot.utils.SpringUtils;

/**
 * spring session配置
 * @author xiongcong
 * @date 2019-03-18
 */
@Configuration  
@EnableRedisHttpSession
public class RedisSessionConfig {
    @Autowired
    private RedisOperationsSessionRepository redisOperationsSessionRepository;
    
    @Value("${server.servlet.session.timeout}")
    private int timeout = 1800;
    
    @Value("${spring.session.redis.namespace}")
    private String namespace = "";
    
    /**
     * timeout ： session得超时时间
     * namespace ： 存储在redis里的空间，多个工程使用同一个redis时需设置不一样
     * @author xiongcong 2019-05-17
     */
    @PostConstruct
    public void configuration() {
        redisOperationsSessionRepository.setDefaultMaxInactiveInterval(timeout);
        redisOperationsSessionRepository.setRedisKeyNamespace("spring:session:" + namespace);
    }
    
    /**
     * Redis内session过期事件监听
     */
    @EventListener
    public void onSessionExpired(SessionExpiredEvent event) {
        //String sessionId = event.getSessionId();
        
        AdminPrincipal user = (AdminPrincipal)event.getSession().getAttribute(AdminConstants.SESSION_USER_INFO);
        if (user != null) {
            RedisUtils.del(AdminConstants.REDIS_PREFIX_TOKEN + user.getToken());
            if (user.getLoginId() != null) {
                SysLoginLogService sysLoginLogService = SpringUtils.getBean(SysLoginLogService.class);
                sysLoginLogService.addLoginoutLog(user.getLoginId(), "会话信息失效退出");
                AdminConstants.MAP_LOGIN_TIP_MSG.put(event.getSession().getId(), "会话已失效，请重新登录");
            }
        }
    }


    /**
     * Redis内session删除事件监听
     */
    @EventListener
    public void onSessionDeleted(SessionDeletedEvent event) {
        //String sessionId = event.getSessionId();
    }

    /**
     * Redis内session保存事件监听
     */
    @EventListener
    public void onSessionCreated(SessionCreatedEvent event) {
        //String sessionId = event.getSessionId();
    }
}
